package com.example.day03_mvp.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.day03_mvp.LoadingDialog;
import com.example.day03_mvp.utils.ToastUtil;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseLazyFragment<P extends BasePresenter> extends Fragment implements BaseView {
    private Unbinder munbinder;
    protected P mPresenter;
    private LoadingDialog mloadingDialog;
    private boolean mIsVisibleToUser;
    private  boolean mIsViewCreated;
    private boolean mDataLoaded;
    private View mView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView==null){
            mView=inflater.inflate(getLayout(),null);
            munbinder= ButterKnife.bind(this,mView);
            mPresenter=initPresenter();
            if (mPresenter!=null){
                mPresenter.bindView(this);
            }
            initView(mView);
            mIsViewCreated=true;
            lazyLoad();
            initListener();
        }
        return mView;
    }
    private void lazyLoad(){
        if (mIsViewCreated&&mIsVisibleToUser&&!mDataLoaded){
            mDataLoaded=true;
            initData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.mIsVisibleToUser=isVisibleToUser;
        lazyLoad();
    }

    protected abstract void initListener();

    protected abstract void initData();

    protected abstract void initView(View mView);

    protected abstract P initPresenter();

    protected abstract int getLayout();

    @Override
    public void onDestroy() {
        super.onDestroy();
        munbinder.unbind();
        if (mPresenter!=null){
            mPresenter.dsetroy();
            mPresenter=null;
        }
        hideLoading();
    }

    @Override
    public void showToast(String str) {
        ToastUtil.showShort(str);
    }
    public void hideLoading(){
        if (mloadingDialog!=null){
            mloadingDialog.dismiss();
        }
    };
}
